package com.boruan.shengtangfeng.admin.service.impl;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.boruan.shengtangfeng.admin.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.admin.service.ILoginService;
import com.boruan.shengtangfeng.core.dao.IConfigDao;
import com.boruan.shengtangfeng.core.dao.ISystemUserDao;
import com.boruan.shengtangfeng.core.entity.SystemUser;
import com.boruan.shengtangfeng.core.utils.Consts;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.StringUtils;
import com.boruan.shengtangfeng.core.utils.UserUtil;
import com.boruan.shengtangfeng.core.vo.LoginResult;
import com.boruan.shengtangfeng.core.vo.SystemUserVo;
import com.boruan.shengtangfeng.core.vo.mapper.SystemUserVoMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * @author: 刘光强
 * @Description:
 * @date:2020年3月10日 上午11:14:10
 */
@SuppressWarnings("all")
@Service
@Slf4j
@Transactional(readOnly = true)
public class LoginService implements ILoginService {
	@Autowired
	private ISystemUserDao systemUserDao;
	@Autowired
	private IConfigDao configDao;
	@Value("${aliyun.sms.product}")
	private String product;
	@Value("${aliyun.sms.domain}")
	private String domain;
	@Value("${aliyun.sms.accessKeyId}")
	private String accessKeyId;
	@Value("${aliyun.sms.accessKeySecret}")
	private String accessKeySecret;
	@Value("${aliyun.sms.templateCode.register}")
	private String templateCodeRegister;
	@Value("${aliyun.sms.templateCode.login}")
	private String templateCodeLogin;
	@Value("${aliyun.sms.templateCode.changePassword}")
	private String templateCodeChangePassword;
	@Value("${aliyun.sms.signName}")
	private String signName;

	@Autowired
	private JwtUtil jwtUtil;
	@Value("${jwt.tokenHead}")
	private String tokenHead;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Override
	@Transactional(readOnly = false)
	public GlobalReponse<LoginResult> passwordLogin(String loginName, String password) {
		SystemUser user = systemUserDao.findByLoginName(loginName);
		if (user == null) {
			return GlobalReponse.fail("用户不存在");
		}
		boolean match = UserUtil.match(password, user.getPassword(), user.getSalt());
		LoginResult result = new LoginResult();
		if (match) {
			systemUserDao.updateById(user);
			result.setStatus(1);
			result.setAdmin(SystemUserVoMapper.MAPPER.toVo(user));
			String token = jwtUtil.generateToken(user.getId(), user.getLoginName(), user.getName(), null);
			result.setToken(tokenHead + token);
			return GlobalReponse.success(result);
		}
		return GlobalReponse.fail("密码错误");
	}

	/**
	 * @param :type:1用户注册验证码, 2登录确认验证码, 3修改密码验证码
	 * @author: 刘光强
	 * @Description: 获取验证码
	 * @date:2020年3月10日 上午11:14:10
	 */
	@Override
	public GlobalReponse<String> getVerficationCode(String mobile, Integer type) {
		GlobalReponse globalReponse = new GlobalReponse();
		if (StringUtils.isRealBlank(mobile)) {
			return globalReponse.fail("手机号不能为空！");
		}
		try {
			// 初始化acsClient,暂不支持region化
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);
			SendSmsRequest request = new SendSmsRequest();
			request.setPhoneNumbers(mobile);
			request.setSignName("兔兔油");
			if (type == 1) {
				request.setTemplateCode("SMS_173145866");
			} else if (type == 2) {
				request.setTemplateCode("SMS_173145868");
			} else if (type == 3) {
				request.setTemplateCode("SMS_173145865");
			}
			String code = StringUtils.createCharacterNumber();
			code = "0000";
			request.setTemplateParam("{code:" + code + "}");
			redisTemplate.opsForValue().set(Consts.sendCode + mobile, code, 5, TimeUnit.MINUTES);
			return globalReponse.success("验证码发送成功", code);
			// SendSmsResponse response = acsClient.getAcsResponse(request);
			/*
			 * if("OK".equals(response.getCode())) {
			 * redisTemplate.opsForValue().set(Consts.sendCode + mobile, code, 5,
			 * TimeUnit.MINUTES); return globalReponse.success("验证码发送成功",code); } else {
			 * return globalReponse.fail(response.getMessage()); }
			 */
		} catch (Exception e) {
			e.printStackTrace();
			return GlobalReponse.fail("发送验证码失败！");
		}
	}

	/**
	 * @author: 刘光强
	 * @Description: 处理绑定手机号
	 * @date:2020年3月10日 上午11:14:10
	 */
	@Override
	@Transactional(readOnly = false)
	public GlobalReponse<SystemUserVo> bindingMobile(String mobile, String authCode, Long adminId) {

		String codeRedis = (String) redisTemplate.opsForValue().get(Consts.sendCode + mobile);
		if (!StringUtils.equals(authCode, codeRedis)) {
			return GlobalReponse.fail("验证码错误");
		} else {
			redisTemplate.delete(Consts.sendCode + mobile); // 验证成功删除redis存在的验证码
		}
		SystemUser user = systemUserDao.findByMobile(mobile); // 根据手机号查用户是否注册过
		if (user == null) {
			user = systemUserDao.single(adminId);
			user.setMobile(mobile);
			systemUserDao.updateById(user);
		} else {
			return GlobalReponse.fail("该手机号已绑定其他账号");
		}
		return GlobalReponse.success(SystemUserVoMapper.MAPPER.toVo(user));
	}

	/**
	 * @author: 刘光强
	 * @Description: 验证手机号是否注册过
	 * @date:2020年3月10日 上午11:14:10
	 */
	@Override
	public GlobalReponse<Boolean> verificationMobile(String mobile) {
		SystemUser user = systemUserDao.findByMobile(mobile); // 根据手机号查用户是否注册过
		if (user != null) {
			return GlobalReponse.success(true);
		}
		return GlobalReponse.success(false);

	}

	/**
	 * @author: 刘光强
	 * @Description: 忘记密码或者修改密码
	 * @date:2020年3月10日 上午11:14:10
	 */
	@Override
	@Transactional(readOnly = false)
	public GlobalReponse updatePassword(String mobile, String password, String authCode) {
		String codeRedis = (String) redisTemplate.opsForValue().get(Consts.sendCode + mobile);
		if (!StringUtils.equals(authCode, codeRedis)) {
			return GlobalReponse.fail("验证码错误");
		} else {
			redisTemplate.delete(Consts.sendCode + mobile); // 验证成功删除redis存在的验证码
		}
		SystemUser user = systemUserDao.findByMobile(mobile); // 根据手机号查用户是否注册过
		if (user != null) {
			user.setSalt(UserUtil.getSalt());
			user.setPassword(UserUtil.entryptPassword(password, user.getSalt()));
			systemUserDao.updateById(user);
			return GlobalReponse.success();
		} else {
			return GlobalReponse.fail("用户不存在");
		}

	}

	/**
	 * 审核端修改密码
	 *
	 * @param password
	 * @param newPassword
	 * @param newPasswordAgain
	 * @return
	 */
	@Override
	@Transactional(readOnly = false)
	public GlobalReponse updatePasswordForNew(Long userId,String password, String newPassword, String newPasswordAgain) {
		if (!newPassword.equals(newPasswordAgain)){
			return GlobalReponse.fail("两次输入的新密码不一致");
		}
		SystemUser systemUser = systemUserDao.createLambdaQuery().andEq(SystemUser::getId,userId).single(); // 根据手机号查用户是否注册过

		if (systemUser != null) {
			boolean match = UserUtil.match(password, systemUser.getPassword(), systemUser.getSalt());
			if (!match){
				return GlobalReponse.fail("原密码输入错误，请重新处输入");
			}
			systemUser.setSalt(UserUtil.getSalt());
			systemUser.setPassword(UserUtil.entryptPassword(newPassword, systemUser.getSalt()));
			systemUserDao.updateById(systemUser);
			return GlobalReponse.success("修改成功");
		} else {
			return GlobalReponse.fail("用户不存在");
		}
	}

}
